package com.guojian.jdbc.mapper;

import org.springframework.dao.TypeMismatchDataAccessException;
import org.springframework.jdbc.IncorrectResultSetColumnCountException;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import org.springframework.util.ClassUtils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class SingleColumnRowMapperX<T> extends SingleColumnRowMapper<T> {

    private Class<?> requiredType;

    @SuppressWarnings("unchecked")
	@Override
    public T mapRow(ResultSet rs, int rowNum) throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
        int nrOfColumns = rsmd.getColumnCount();
        if (nrOfColumns != 2) {
            throw new IncorrectResultSetColumnCountException(2, nrOfColumns);
        }

        Object result = getColumnValue(rs, 2, this.requiredType);
        if (result != null && this.requiredType != null && !this.requiredType.isInstance(result)) {
            try {
                return (T) convertValueToRequiredType(result, this.requiredType);
            } catch (IllegalArgumentException ex) {
                throw new TypeMismatchDataAccessException("Type mismatch affecting row number " + rowNum + " and column type '" + rsmd.getColumnTypeName(2) + "': " + ex.getMessage());
            }
        }
        return (T) result;
    }


    public SingleColumnRowMapperX(Class<T> requiredType) {
        this.requiredType = ClassUtils.resolvePrimitiveIfNecessary(requiredType);
    }
}
